import COS from 'cos-js-sdk-v5'
import { tencentCosTmp } from '/@/api/admin'

const upload = (file: any, Key: string) => {
  return new Promise((resolve, reject) => {
    tencentCosTmp({}).then((res: any) => {
      console.log('获取腾讯云COS临时秘钥', res);
      let info = res.data.info
      var cos = new COS({
        getAuthorization: (options, callback) => {
          callback({
            TmpSecretId: info.TmpSecretId,
            TmpSecretKey: info.TmpSecretKey,
            SecurityToken: info.SecurityToken,
            StartTime: info.StartTime,
            ExpiredTime: info.ExpiredTime
          })
        }
      })
      cos.putObject({
        Bucket: info.Bucket, /* 必须 */
        Region: info.Region, /* 存储桶所在地域，必须字段 */
        Key: Key, /* 必须 */
        StorageClass: 'STANDARD',
        Body: file,
        onProgress: progressData => {
          console.log('上传中', JSON.stringify(progressData));
        }
      }, (err, data) => {
        resolve(err || { statusCode: data.statusCode, url: import.meta.env.VITE_FILE_API + Key })
      })
    }).catch((err:any) => {
      reject(err)
    })
  })
}
export default upload
